
import { Message } from 'element-ui';
import router from '@/router/index';

// 用户 注册，登陆，退出
const serviceId = 'qczzlg'; // 替换成你的 serviceId
const localSessionKey = `light:${serviceId}:local-session`;

import {register, login, logout} from "@/api";

// token存放至sessionStorage中的key名
const SESSION_KEY_JWT = 'jwtToken';
const SESSION_KEY_USER = 'user';
const SESSION_KEY_INDEX_ROUTER = 'home';
let user = {};

const state={
  user,
  token: window.sessionStorage.getItem(SESSION_KEY_JWT) || 'null',
  indexRouter: window.sessionStorage.getItem(SESSION_KEY_INDEX_ROUTER) || {},
};
const mutations={
  // 设置token
  AUTH_SET_TOKEN(state, token = false) {
    state.token = token;
    window.sessionStorage.setItem(SESSION_KEY_JWT, token);
  },
  /* 设置用户 */
  AUTH_SET_USER(state, user) {
    // if (!user.enterprise) {
    //   state.userEnt = '';
    // }
    state.user = user;
    window.sessionStorage.setItem(SESSION_KEY_USER, JSON.stringify(user));
  },
  // 设置用户首页路由
  AUTH_SET_INDEX_ROUTER(state, router) {
    state.indexRouter = router;
    window.sessionStorage.setItem(SESSION_KEY_INDEX_ROUTER, router);
  },
  /* 退出系统 */
  AUTH_LOGOUT(state) {
    window.sessionStorage.removeItem(SESSION_KEY_JWT);
    window.sessionStorage.removeItem(SESSION_KEY_USER);
    window.sessionStorage.removeItem(SESSION_KEY_INDEX_ROUTER);
    state.token = 'null';
    // router.replace('/login');

    //  打包时注意不同域时的
    /** 【window.location】返回信息参考
     * hash: "#/index"
     * host: "localhost:8080"
     * hostname: "localhost"
     * href: "http://localhost:8080/#/index"
     * origin: "http://localhost:8080"
     * pathname: "/"
     * port: "8080"
     * protocol: "http:"
     */
    window.location.replace(`${window.location.protocol}//${window.location.host}/#/login`);
  },
};
const actions={
  // 登录
  AUTH_LOGIN({ commit }, params) {
    const keyParams = {
      username: params.uid,
      password: params.pid
    };
    login(localSessionKey, keyParams).then(res=>{
      // code: 200
      // data: {
      //   userInfo: {
      //     agent: null
      //     avatar: null
      //     createAt: 1644242452404
      //     createdAt: 1644242452404
      //     email: null
      //     expireAt: 1645540150712
      //     firstProvider: "username"
      //     intro: null
      //     lastIp: null
      //     lastLogin: 1644242452479
      //     loginAt: 1644244150712
      //     loginCount: 2
      //     nickname: ""
      //     phoneNumber: null
      //     status: true
      //     updatedAt: 1644242452479
      //     username: "testUser1"
      //     _id: "620126145fc68c020d7facfd"
      //   }
      // }
      // msg: "success"
      if (res.data.msg == 'success' && res.data.code === 200) {
        user = res.data.data.userInfo;
        let tokenJWT = res.data.data.authorization;
        // console.log('user',user);
        // 记住密码
        if (params.remember) {
          window.localStorage.setItem('REMEMBER_PWD', 'true');
        } else {
          window.localStorage.removeItem('REMEMBER_PWD');
        }
        /** 2.2
           *   2.2.1 记录token
           *   2.2.2 登录接口返回的用户数据存储 state.user
           *   2.2.3 一是将登录接口返回的用户数据 user 存储在 sessionStorage
           *         二是将用户数据中的 loginID 字段存到 localStorage
           */
        const homeUrl = '/home';
        commit('AUTH_SET_TOKEN', tokenJWT ? tokenJWT : 'aabbccddeeffgg'); // 此处token 需要后端配合
        commit('AUTH_SET_USER', user);
        commit('AUTH_SET_INDEX_ROUTER', homeUrl);
        // 登录后的页面
        router.replace(homeUrl);
        Message({
          type: 'success',
          message: '登陆成功',
        });
      } else {
        Message({
          type: 'warning',
          message: res.data.msg,
        });
      }
    })
  },
  // 退出（也需要调接口）
  AUTH_LOGOUT2({ commit }) {
    logout(localSessionKey).then(res=>{
        // code: 200
        // data: {
        //   userInfo: {
        //     success: true
        //   }
        // }
        // msg: "success"
        // console.log(res);
        // debugger;
        if (res.data.msg == 'success' && res.data.code === 200) {
          commit('AUTH_LOGOUT');
        }
    });
  },
  // 注册
  AUTH_REGISTER({ commit }, params) {
    register(localSessionKey, params).then(res=>{
      // code: 200
      // data: {
      //   userInfo: {
      //     isLogin: true
      //     sessionKey: "light:qczzlg:local-session"
      //     userInfo: {
      //       agent: null
      //       avatar: null
      //       createAt: 1644242452404
      //       createdAt: 1644242452404
      //       email: null
      //       expireAt: 1645538452479
      //       firstProvider: "username"
      //       intro: null
      //       lastIp: null
      //       lastLogin: null
      //       loginAt: 1644242452479
      //       loginCount: 1
      //       nickname: ""
      //       phoneNumber: null
      //       status: true
      //       updatedAt: 1644242452404
      //       username: "testUser1"
      //       _id: "620126145fc68c020d7facfd"
      //     }
      //   }
      // }
      // msg: "success"
      // debugger;
      //console.log('res', res);
      if (res.data.msg == 'success' && res.data.code === 200) {
        Message.success('注册成功，即将跳转登陆页面...');
        // 跳转到登陆页
        router.replace('/login');
      } else {
        if (res.data.code == 500 &&
         res.data.msg=='Register failed because of this session has already login, please checkout session is valid') {
          Message({
            type: 'warning',
            message: '已登录状态，不允许注册，请先退出登陆',
          });
        } else {
          Message({
            type: 'warning',
            message: '哎呀，服务器正忙，请稍后再试',
          });
        }
      }
    })
  }

};
const getters={
  userInfo(state){
    return state.user  || {}
  }

};

export default {
    state,
    mutations,
    actions,
    getters
}